package cn.dliyy.security.shiro;


import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import cn.dliyy.warehouse.bean.Ssubject;
import cn.dliyy.warehouse.dao.EntityIdDao;

/**
 * 安全相关实体的管理类,包括用户和权限组.
 * 
 * @author calvin
 */
// Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional(readOnly = true)
public class AccountManager {

	private static Logger logger = LoggerFactory
			.getLogger(AccountManager.class);
	@Resource
	private EntityIdDao userDao;
	@Resource
	private EntityIdDao groupDao;
	@Resource
	private MyRealm shiroRealm;

	// -- User Manager --//
	public Ssubject getUser(String id) {
		return (Ssubject) userDao.getOne(Ssubject.class, id);
	}

	@Transactional(readOnly = false)
	public void saveUser(Ssubject entity) {
		userDao.save(entity);
		shiroRealm.clearCachedAuthorizationInfo(entity.getUsername());
	}

	/**
	 * 删除用户,如果尝试删除超级管理员将抛出异常.
	 */
	@Transactional(readOnly = false)
	public void deleteUser(Long id) {
		if (isSupervisor(id)) {
			logger.warn("操作员{}尝试删除超级管理员用户", SecurityUtils.getSubject()
					.getPrincipal());
		}
		userDao.delete(id);
	}

	/**
	 * 判断是否超级管理员.
	 */
	private boolean isSupervisor(Long id) {
		return id == 1;
	}

	/*
	 * public List<UserEntity> getAllUser() { return (List<UserEntity>)
	 * userDao.(new Sort(Direction.ASC, "id")); }
	 */

	/*
	 * public User findUserByLoginName(String loginName) { return
	 * userDao.findByLoginName(loginName); }
	 */

	// -- Group Manager --//
	/*
	 * public Group getGroup(Long id) { return groupDao.findOne(id); }
	 * 
	 * public List<Group> getAllGroup() { return (List<Group>)
	 * groupDao.findAll((new Sort(Direction.ASC, "id"))); }
	 * 
	 * @Transactional(readOnly = false) public void saveGroup(Group entity) {
	 * groupDao.save(entity); shiroRealm.clearAllCachedAuthorizationInfo(); }
	 * 
	 * @Transactional(readOnly = false) public void deleteGroup(Long id) {
	 * groupDao.delete(id); shiroRealm.clearAllCachedAuthorizationInfo(); }
	 * 
	 * @Autowired public void setUserDao(UserDao userDao) { this.userDao =
	 * userDao; }
	 */

	/*
	 * @Autowired public void setGroupDao(GroupDao groupDao) { this.groupDao =
	 * groupDao; }
	 * 
	 * @Autowired(required = false) public void setShiroRealm(ShiroDbRealm
	 * shiroRealm) { this.shiroRealm = shiroRealm; }
	 */
}
